package nix.bs.web.servlet;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nix.bs.domain.Cart;
import nix.bs.domain.User;
import nix.bs.service.UserException;
import nix.bs.service.UserService;
import nix.commons.CommonUtils;
import nix.mail.Mail;
import nix.mail.MailUtils;
import nix.servlet.BaseServlet;

public class UserServlet extends BaseServlet {

	private UserService userService = new UserService();

	public String regist(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// 接收封装
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		form.setUid(CommonUtils.uuid());
		form.setCode(CommonUtils.uuid() + CommonUtils.uuid());
		// 校验
		Map<String, String> errors = new HashMap<String, String>();
		if (form.getUsername() == null || form.getUsername().trim().isEmpty()) {
			errors.put("username", "用户名不能为空！");
		} else if (form.getUsername().length() < 3
				|| form.getUsername().length() > 16) {
			errors.put("username", "用户名长度必须在3至16位！");
		}
		if (form.getPassword() == null || form.getPassword().trim().isEmpty()) {
			errors.put("password", "密码不能为空！");
		} else if (form.getPassword().length() < 3
				|| form.getPassword().length() > 16) {
			errors.put("password", "密码长度必须在3至16位！");
		}
		if (form.getEmail() == null || form.getEmail().trim().isEmpty()) {
			errors.put("email", "Email不能为空！");
		} else if (form.getEmail().length() < 5
				|| form.getEmail().length() > 32) {
			errors.put("email", "Email长度必须在5至16位！");
		} else if (!form.getEmail().matches("\\w+@\\w+\\.\\w+")) {
			errors.put("email", "Email格式不正确！");
		}
		if (errors.size() > 0) {
			request.setAttribute("errors", errors);
			request.setAttribute("form", form);
			return "f:/bs/jsps/user/regist.jsp";
		}
		// 注册
		try {
			userService.regist(form);
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("form", form);
			return "f:/bs/jsps/user/regist.jsp";
		}
		// 发送激活邮件
		Properties props = new Properties();
		props.load(this.getClass().getClassLoader()
				.getResourceAsStream("email_template.properties"));
		Session session = MailUtils.createSession(props.getProperty("host"),
				props.getProperty("uname"), props.getProperty("pwd"));
		Mail mail = new Mail(props.getProperty("from"), form.getEmail(),
				props.getProperty("subject"), MessageFormat.format(
						props.getProperty("content"), form.getCode()));
		try {
			MailUtils.send(session, mail);
		} catch (MessagingException e) {

		}

		request.setAttribute("msg", "恭喜，注册成功！请前往邮件激活。");
		return "f:/bs/jsps/msg.jsp";
	}

	public String active(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String code = request.getParameter("code");
		try {
			userService.active(code);
			request.setAttribute("msg", "恭喜您激活成功！");
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
		}
		return "f:/bs/jsps/msg.jsp";
	}

	public String login(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 接收封装
		User form = CommonUtils.toBean(request.getParameterMap(), User.class);
		// 校验
		Map<String, String> errors = new HashMap<String, String>();
		if (form.getUsername() == null || form.getUsername().trim().isEmpty()) {
			errors.put("username", "用户名不能为空！");
		} else if (form.getUsername().length() < 3
				|| form.getUsername().length() > 16) {
			errors.put("username", "用户名长度必须在3至16位！");
		}
		if (form.getPassword() == null || form.getPassword().trim().isEmpty()) {
			errors.put("password", "密码不能为空！");
		} else if (form.getPassword().length() < 3
				|| form.getPassword().length() > 16) {
			errors.put("password", "密码长度必须在3至16位！");
		}
		if (errors.size() > 0) {
			request.setAttribute("errors", errors);
			request.setAttribute("form", form);
			return "f:/bs/jsps/user/login.jsp";
		}
		// 登陆
		try {
			User user = userService.login(form);
			request.getSession().setAttribute("session_user", user);
			// 创建购物车
			request.getSession().setAttribute("cart", new Cart());
			return "r:/bs/index.jsp";
		} catch (UserException e) {
			request.setAttribute("msg", e.getMessage());
			request.setAttribute("form", form);
			return "f:/bs/jsps/user/login.jsp";
		}
	}

	public String quit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 销毁Session
		request.getSession().invalidate();
		return "r:/bs/index.jsp";
	}
}
